# -*- coding: utf-8 -*-
from sanic.views import HTTPMethodView
from utils.myCache import Cache
from sanic.response import json as JsonResponse
from utils.myResFormat import ResultJson, ResultCode
import uuid, json
from config import config
import hashlib

# 配置缓存
RedisClient = Cache().select('redis').current_db


class HashCipher:

    @staticmethod
    def md5(message):
        """
        Returns the MD5 hash of the message
        """
        return hashlib.md5(message.encode()).hexdigest()

# 类试图
class GetContentView(HTTPMethodView):
    """获取数据，playwright处理相关结果"""

    def post(self, request):
        rev_data = request.json

        uid = "worker_order_" + HashCipher.md5(str(rev_data["url"]))
        rev_data['uid'] = uid

        # 推入任务队列,又worker执行
        RedisClient.lpush(config.WORKER_QUEUE, json.dumps(rev_data))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=uid).result)


class QueryResultView(HTTPMethodView):
    """通过uid查询处理的结果"""

    def get(self, request):
        uid = request.args.get("uid")
        result = RedisClient.get(uid)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=result).result)
